﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using BUS;
using DAO;
using AjaxChatService.Models;

namespace AjaxChatService.Controllers
{
    [HttpHeader("Access-Control-Allow-Origin", "*")]
    public class MessagesController : ApiController
    {
        MessageBUS messageBUS = new MessageBUS();

        public IEnumerable<Message> GetMessages(int userId)
        {
            var messages = messageBUS.GetMessages(userId).ToList();

            return messages;         
        }

        public IEnumerable<MessageModel> GetMessages([FromUri]int[] roomIds)
        {
            var messages = messageBUS.GetMessages(roomIds).Select(m => new MessageModel
                                                                       {
                                                                           Text = m.Text,
                                                                           RoomId = m.RoomId.GetValueOrDefault(),
                                                                           UserId = m.UserId.GetValueOrDefault(),
                                                                           UserName = m.User.UserName
                                                                       });
            
            return messages;
        }

        // POST api/Messages
        public HttpResponseMessage PostMessage(Message message)
        {
            if (ModelState.IsValid)
            {
                messageBUS.AddMessage(message);

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, message);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = message.Id }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}